<template>
  <j-modal
    :title="title"
    :width="width"
    :visible="visible"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    :footer="footer"
    cancelText="关闭">

    <a-row :gutter="10" type="flex" justify="space-around" align="middle">
      <a-col :span="7">
        <a-card title="可选应用" :bodyStyle="bodyStyle" style="overflow: auto;max-height: 60vh;" ref="appCard">
          <a-input-search v-model="appValue" @search="onSearch" style="width:100%;margin-top: 10px" placeholder=""/>
          <a-tree
            :checkable="true"
            :selectedKeys="selectedKeys"
            :checkedKeys="checkedKeys"
            :treeData="appTree"
            @check="onCheck"
          />
        </a-card>
      </a-col>

      <a-col :span="1">
        <a-button type="primary" @click="selectApp" size="small">
          <a-icon type="right" />
        </a-button>
        <a-button type="default" @click="cancelSelectRole" size="small" style="margin-top:3px">
          <a-icon type="left" />
        </a-button>
      </a-col>

      <a-col :span="8">
        <a-card title="已选应用默认角色" :bodyStyle="bodyStyle" style="overflow: auto;max-height: 60vh;">
          <a-tree
            :checkable="true"
            :selectedKeys="selectedKeysRole"
            :checkedKeys="checkedKeysRole"
            :treeData="treeRole"
            @check="onCheckRole"
            @select="onSelectRole"
          />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card title="菜单/按钮权限" :bodyStyle="bodyStyle" style="overflow: auto;max-height: 60vh;">
          <a-tree
            checkable
            :selectedKeys="selectedKeysPermission"
            :checkedKeys="checkedKeysPermission"
            :treeData="permissionTree"
            @check="onCheckPermission"
            @expand="expandPermission"
            :checkStrictly="false"
            :expandedKeys="expandedKeys"
          />
        </a-card>
      </a-col>
    </a-row>
  </j-modal>
</template>

<script>
  import { getAppTree, listTenantAppTree, getPermissionTree, getTenantPermission, saveTenantPermission } from './service'
  import { TENANT_ID, IS_SUPER_TENANT } from '@/store/mutation-types';
  import Vue from 'vue';

  export default {
    name: 'TenantAppModal',
    components: {
    },
    data () {
      return {
        title: '配置应用',
        width: 960,
        visible: false,

        footer: true,

        tenantId: '',

        appValue: '',

        checkedKeys: [],
        selectedKeys: [],
        appTree: [],

        selectedKeysRole: [],
        checkedKeysRole: [],
        existTreeRole: [],
        treeRole: [],

        selectedKeysPermission: [],
        checkedKeysPermission: [],
        permissionTree: [],
        permissionIds: [],
        expandedKeys: [],

        savePermissions: {},
        currentAppId: '',

        bodyStyle: { 'min-height': '500px' },

        url: {
        }
      }
     },
    watch: {
      tenantId() {
        this.footer = Vue.ls.get(IS_SUPER_TENANT) || Vue.ls.get(TENANT_ID) !== this.tenantId ? undefined : null
      }
    },
    methods: {
      close () {
        this.$emit('close');
        this.visible = false;
      },
      edit (record) {
        this.tenantId = record.id;
        this.appValue = ''

        this.visible = true

        this.checkedKeys = [];
        this.loadTree('', this.tenantId);

        this.selectedKeysRole = [];
        this.checkedKeysRole = [];
        this.checkedKeys = [];
        this.loadTreeRole(record.id);

        this.checkedKeysPermission = [];
        this.permissionTree = [];
        this.getTenantPermission(record.id)
        this.$nextTick(() => {
          this.$refs.appCard.$el.scrollTop = 0
        })
      },
      handleOk () {
        let param = {
          tenantId: this.tenantId
        }
        let details = [];
        let authFlag = false;
        // 通过已选默认角色保存
        this.treeRole.forEach((item, index, array) => {
          if (item.title.indexOf('统一认证') !== -1) {
            authFlag = true;
          }
          let appId = item.appId;
          let detail = { appId: appId };
          detail.parentRoleId = item.roleId;
          if (this.existTreeRole[appId] !== undefined) {
            detail.roleId = this.existTreeRole[appId].roleId;
            detail.parentRoleId = item.parentRoleId;
          }
          let permissionInfo = this.savePermissions[appId];
          if (permissionInfo === undefined || permissionInfo === null) {
            detail.permissionIds = [];
          } else {
            detail.permissionIds = permissionInfo.permissionIds;
          }
          details.push(detail);
        })
        if (details.length === 0) {
          this.$message.error('请选择应用默认角色');
        } else if (!authFlag) {
          this.$message.error('必须选择统一认证中心默认角色');
        } else {
          param['details'] = details;
          saveTenantPermission(this.tenantId, param).then((res) => {
            if (res.success) {
              this.$message.success('保存成功');
              this.close();
            } else {
              this.$message.error(res.message);
            }
          })
        }
      },
      handleCancel () {
        this.close()
      },
      loadTree(appName, tenantId) {
        let that = this
        appName = appName || '';
        getAppTree({ name: appName, tenant_id: tenantId }).then((res) => {
          if (res.success) {
            that.appTree = res.result;
          } else {
            this.$message.error(res.message)
          }
        })
      },
      onSearch(value) {
        this.loadTree(value, this.tenantId)
      },
      onCheck(checkedKeys) {
        this.checkedKeys = checkedKeys
      },

      loadTreeRole(tenantId) {
        let that = this
        listTenantAppTree(tenantId).then((res) => {
          if (res.success) {
            that.treeRole = res.result;
            that.existTreeRole = {};
            res.result.forEach(function (item) {
              that.existTreeRole[item.appId] = item
            })
          } else {
            that.$message.error(res.message)
          }
        })
      },
      onCheckRole(checkedKeys) {
        this.checkedKeysRole = checkedKeys
      },
      onSelectRole(selectedKeys) {
        if (selectedKeys.length > 0) {
          let roleId = selectedKeys[0];
          let appId;
          let queryRoleId;
          this.treeRole.forEach(function (item) {
            if (roleId === item.key) {
              appId = item['appId'];
              if (item['parentRoleId'] && item['parentRoleId'] > 0) {
                queryRoleId = item['parentRoleId'];
              } else {
                queryRoleId = roleId;
              }
            }
          })
          this.currentAppId = appId;
          this.getPermissionTree(queryRoleId, appId)
        } else {
          this.currentAppId = '';
          this.permissionTree = [];
          this.permissionIds = [];
          this.checkedKeysPermission = [];
        }
        this.selectedKeysRole = selectedKeys
      },

      selectApp() {
        let that = this;
        if (that.checkedKeys.length === 0) {
          this.$message.warning('请选择可选应用')
          return
        }
        let selectedRoleId = [];
        let selectedRoleMap = {}
        that.treeRole.forEach(function (item) {
          if (item.parentRoleId && item.parentRoleId > 0) {
            selectedRoleId.push(item.parentRoleId);
            selectedRoleMap[item.parentRoleId] = item
          } else {
            selectedRoleId.push(item.key);
            selectedRoleMap[item.key] = item
          }
        })
        this.appTree.forEach(function (item) {
          let isSelected = that.checkedKeys.findIndex(key => key === item.key) !== -1;
          if (isSelected && item['roleId']) {
            if (selectedRoleId.findIndex(key => key === item.roleId) === -1) {
              selectedRoleId.push(item['roleId'])
            }
          }
        });

        let treeRole = [];
        selectedRoleId.forEach(function (key) {
          let selected = false
          that.appTree.forEach(function (item) {
            if (item.roleId && item.roleId === key) {
              treeRole.push({ key: item['roleId'], title: item['roleName'], value: item['roleId'], tenantId: that.tenantId, appId: item['appId'], roleId: item['roleId'] });
              selected = true
            }
          })
          if (!selected) {
            treeRole.push(selectedRoleMap[key])
          }
        })

        let treeRoleResort = []
        that.appTree.forEach(function (itemA) {
          treeRole.forEach(function (itemB) {
            if (itemA.roleId && itemA.roleId === itemB.key) {
              treeRoleResort.push(itemB);
            }
          })
        })
        treeRole.forEach(function (itemB) {
          let selected = false
          treeRoleResort.forEach(function (itemA) {
            if (itemA.key === itemB.key) {
              selected = true
            }
          })
          if (!selected) {
            treeRoleResort.push(itemB)
          }
        })

        that.treeRole = treeRoleResort
      },
      cancelSelectRole() {
        let that = this;
        if (that.checkedKeysRole.length === 0) {
          this.$message.warning('请选择已选应用默认角色')
          return
        }
        let leftRoleTree = [];
        that.treeRole.forEach(function (item) {
          let isSelected = that.checkedKeysRole.findIndex(key => key === item.key) !== -1;
          if (isSelected) {
             if (that.selectedKeysRole.findIndex(key => key === item.key) !== -1) {
               that.permissionTree = [];
               that.checkedKeysPermission = [];
               that.selectedKeysRole = []
             }
             if (that.savePermissions[item.appId] !== undefined) {
               delete that.savePermissions[item.appId];
             }
          } else {
            leftRoleTree.push(item);
          }
        });

        this.checkedKeysRole = [];
        this.treeRole = leftRoleTree;
      },

      getTenantPermission(tenantId) {
        let that = this;
        getTenantPermission(tenantId).then((res) => {
          if (res.success) {
            that.savePermissions = {};
            res.result.forEach(function (item) {
              if (that.savePermissions[item.appId] === undefined) {
                that.savePermissions[item.appId] = { permissionIds: [], leafPermission: [] };
              }
              that.savePermissions[item.appId]['permissionIds'].push(item.permissionId);
              if (item.isLeaf === 1) {
                that.savePermissions[item.appId]['leafPermission'].push(item.permissionId);
              }
            });
          } else {
            this.$message.error(res.message)
          }
        })
      },
      getPermissionTree(roleId, appId) {
        let that = this
        getPermissionTree(roleId).then((res) => {
          if (res.success) {
            this.permissionTree = res.result.permissions;
            this.permissionIds = res.result.permissionIds;
            this.expandedKeys = this.permissionIds
            if (that.savePermissions[appId] !== undefined) {
              that.checkedKeysPermission = that.savePermissions[appId]['leafPermission'];
              that.savePermissions[appId]['parentRoleId'] = roleId;
            } else {
              that.savePermissions[appId] = { permissionIds: [], 'parentRoleId': roleId };
            }
          } else {
            this.$message.error(res.message)
          }
        })
      },
      onCheckPermission(checkedKeys, e) {
        let checked = checkedKeys;
        let halfChecked = e.halfCheckedKeys
        this.checkedKeysPermission = checked;
        this.savePermissions[this.currentAppId].leafPermission = checked;
        this.savePermissions[this.currentAppId].permissionIds = checked.concat(halfChecked);
      },

      checkALL() {
        this.checkedKeysPermission = this.permissionIds
        this.savePermissions[this.currentAppId].permissionIds = this.permissionIds
      },
      cancelCheckALL() {
        this.checkedKeysPermission = []
        this.savePermissions[this.currentAppId].permissionIds = []
      },
      expandAll() {
        this.expandedKeys = this.permissionIds
      },
      closeAll() {
        this.expandedKeys = []
      },
      expandPermission(expandedKeys) {
        this.expandedKeys = expandedKeys
      }
    }
  }
</script>
